/* Copyright (C) 2007-2008  klevgert  http://code.google.com/p/db4o-netbeans/

This file is part of the db4o-netbeans module suite.

db4o-netbeans is free software; you can redistribute it and/or modify it under
the terms of version 2 of the GNU General Public License as published
by the Free Software Foundation and as clarified by db4objects' GPL 
interpretation policy, available at
http://www.db4o.com/about/company/legalpolicies/gplinterpretation/
Alternatively you can write to db4objects, Inc., 1900 S Norfolk Street,
Suite 350, San Mateo, CA 94403, USA.

db4o-netbeans is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. */


package com.db4o.nb.editor.nodes;

import com.db4o.ObjectContainer;
import com.db4o.ext.DatabaseFileLockedException;
import com.db4o.nb.api.Db4oProvider;
import com.db4o.nb.api.QueryData;
import com.db4o.nb.editor.dialogs.NewQueryDialog;
import java.awt.event.ActionEvent;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import org.openide.ErrorManager;
import org.openide.actions.PropertiesAction;
import org.openide.loaders.DataNode;
import org.openide.loaders.DataObject;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.openide.util.actions.SystemAction;
import org.openide.util.lookup.Lookups;

/**
 * Manages a list of query nodes.
 *
 * @author klevgert
 */
public class QueryListNode extends AbstractNode {

  static final String ICON_PATH = "com/db4o/nb/editor/resources/query.gif";

  private List queries;
  
  /** Creates a new instance of QueryListNode */
  public QueryListNode(List queries, DataObject dataObj) {
    super(new QueryListChildren(queries, dataObj), Lookups.fixed( new Object[] { queries, dataObj }));
    
    this.queries = queries;
    
    this.setDisplayName(NbBundle.getMessage(this.getClass(), "Queries"));
    this.setIconBaseWithExtension(ICON_PATH);
  }

  public List getQueries() {
    return queries;
  }
  
  /**
   * Returns the preferred action that will be executed on double click.
   * @return preferred node action
   */
  public Action getPreferredAction() {
    Action retValue = this.getActions(true)[0];
    return retValue;
  }

  /**
   * Gets the action that could be performed on the node.
   * @param b   flag indicating if the menu is a popup 
   * @return Array of actions to execute on the node
   */
  public Action[] getActions(boolean b) {

    Action[] actions = new Action[] { 
      new AddQueryAction(),
      null,
      SystemAction.get(PropertiesAction.class)      
    };
    return actions;
  }
  
  public void reloadChildren() {
    DataObject dataObj = (DataObject) getLookup().lookup( DataObject.class );
    this.setChildren(new QueryListChildren(this.getQueries(), dataObj));
  }
  
  private ObjectContainer getObjectContainer() throws DatabaseFileLockedException {

    Db4oProvider provider = getDb4oProvider();
    ObjectContainer objectContainer = provider.getDatabase().getObjectContainer();
    return objectContainer;
  }
  
  private Db4oProvider getDb4oProvider() {

    DataObject dataObj = (DataObject)this.getParentNode().getLookup().lookup(DataObject.class);
    Db4oProvider provider = (Db4oProvider)dataObj.getCookie(Db4oProvider.class);
    if( provider == null ) {
      ErrorManager.getDefault().log("Severe: No db4o provider found");
    }
    return provider;
  }
  
  
  public static class QueryListChildren extends Children.Keys {

    private List queries;
    private DataObject dataObj;
    
    /** Creates a new instance of DatabaseChildren */
    public QueryListChildren(List queries, DataObject dataObj) {
      
      this.dataObj = dataObj;
      this.queries = queries;
    }

    protected Node[] createNodes(Object obj) {
      
      QueryNode result = new QueryNode( (QueryData)obj, this.dataObj );
      return new Node[] {result};
    }  

    protected void addNotify() {

      setKeys( queries.toArray() );
    }  
  }

  /*
   * Action to add a query to this database node.
   */
  private class AddQueryAction extends AbstractAction {
    
    public AddQueryAction() {
      String name = NbBundle.getMessage(this.getClass(), "AddQuery");
      this.putValue(NAME, name);
    }
    
    public void actionPerformed(ActionEvent e) {

      ObjectContainer objectContainer = QueryListNode.this.getObjectContainer();
      
      NewQueryDialog nqd = new NewQueryDialog(new JFrame(), true);
      nqd.setObjectContainer(objectContainer);
      nqd.setVisible(true);
      if( nqd.getReturnStatus() == NewQueryDialog.RET_OK ) {
        
        DataObject dataObj = ((DataNode)QueryListNode.this.getParentNode()).getDataObject();
        Db4oProvider provider = (Db4oProvider)dataObj.getCookie(Db4oProvider.class);
        
        QueryData query = null;
        if( nqd.getKind().equals( QueryData.KIND_SQL ) ) {
          
          query = provider.createSqlQuery( nqd.getName(), "", nqd.getType() );

        } else {
          
          query = provider.createSodaQuery( nqd.getName(), nqd.getType() );
        }
        QueryListNode.this.getQueries().add(query);        
        dataObj.setModified(true);
        
        QueryListNode.this.setChildren( new QueryListChildren(QueryListNode.this.queries, dataObj));
      }
    }
  }
  
}
